<template>
  <div class="admin-user-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div
                class="text-xs font-weight-bold text-primary text-uppercase mb-1"
              >
                总用户数
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ totalUsers }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-people-fill fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div
                class="text-xs font-weight-bold text-success text-uppercase mb-1"
              >
                活跃用户
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ activeUsers }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-person-check-fill fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div
                class="text-xs font-weight-bold text-info text-uppercase mb-1"
              >
                培训导师
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ trainerCount }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-person-badge fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div
                class="text-xs font-weight-bold text-warning text-uppercase mb-1"
              >
                实习中用户
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ internCount }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-person-plus fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮和筛选器 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="12">
        <el-button
          type="primary"
          class="me-2"
          @click="modalController.openPopup('newUserModal')"
          ><i class="bi bi-person-plus me-1"></i> 创建用户
        </el-button>
        <el-button
          type="info"
          class="me-2"
          @click="handleRoleManagement"
          ><i class="bi bi-shield-lock me-1"></i>
          角色管理
        </el-button>
        <!-- <el-button type="default"
          ><i class="bi bi-upload me-1"></i> 批量导入
        </el-button> -->
      </el-col>
      <!-- <el-col :span="12">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名、邮箱..."
          class="w-100"
          clearable
          @clear="resetFilter"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </el-col> -->
    </el-row>

    <!-- 筛选条件 -->
    <el-card class="box-card shadow-sm mb-4">
      <template #header>
        <div class="card-header">
          <h5 class="mb-0">筛选用户</h5>
        </div>
      </template>
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="角色" style="width: 200px">
              <el-select
                v-model="filterForm.role"
                placeholder="全部角色"
                clearable
                witdh="200px"
              >
                <el-option label="全部角色" value=""></el-option>
                <el-option label="系统管理员" value="admin"></el-option>
                <el-option label="培训导师" value="trainer"></el-option>
                <el-option label="护理学员" value="student"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="状态" style="width: 200px">
              <el-select
                v-model="filterForm.status"
                placeholder="全部状态"
                style="width: 200px"
                clearable
              >
                <el-option label="全部状态" value=""></el-option>
                <!-- <el-option label="活跃" value="active"></el-option>
                <el-option label="未激活" value="inactive"></el-option>
                <el-option label="已锁定" value="locked"></el-option>
                <el-option label="待审核" value="pending"></el-option> -->
                <el-option label="实习" value="intern"></el-option>
                <el-option label="正式" value="formal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="注册时间" style="width: 200px">
              <el-select
                v-model="filterForm.registrationTime"
                placeholder="全部时间"
                clearable
              >
                <el-option label="全部时间" value=""></el-option>
                <el-option label="最近7天" value="7days"></el-option>
                <el-option label="最近30天" value="30days"></el-option>
                <el-option label="最近90天" value="90days"></el-option>
                <el-option label="自定义范围" value="custom"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-end">
            <el-button @click="resetFilter">清空筛选</el-button>
            <el-button type="primary" @click="handleFilter">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="box-card shadow-sm">
      <template #header>
        <div class="card-header">
          <h5 class="mb-0">用户列表</h5>
        </div>
      </template>
      <el-table :data="filteredUserList" stripe style="width: 100%">
        <el-table-column prop="id" label="#" width="50"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)"
              >{{ scope.row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)"
              >{{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间">
          <template #default="{ row }">
            {{ formatDate(row.registerTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录">
          <template #default="{ row }">
            {{ formatDate(row.lastLogin) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <!-- <el-button size="small" @click="handleEdit(scope.row)"
              >编辑
            </el-button> -->
            <el-button
              size="small"
              type="warning"
              @click="handlePermissions(scope.row)"
              >权限
            </el-button>
            <!-- <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="flex justify-between items-center">
          <div class="text-sm text-gray-500">
            {{ paginationText }}
          </div>
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :small="true"
            layout="prev, pager, next"
            :total="totalUsers"
            @current-change="handlePageChange"
          />
        </div>
      </template>
    </el-card>

    <!-- 弹窗组件 -->
    <new-user-modal
      v-model="modalController.popups.newUserModal"
    ></new-user-modal>
    <role-management-modal ref="roleManagementModalRef" />
    <edit-permission-modal ref="editPermissionModalRef" />
    <edit-role-modal v-model="modalController.popups.editRoleModal" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, reactive } from "vue";
import { useUserStore } from "@/stores/user.js";
import NewUserModal from "@/components/alert/admin/NewUserModal.vue";
import { modalControllers } from "@/stores/modalController.js";
import RoleManagementModal from "@/components/alert/admin/RoleManagementModal.vue";
import EditRoleModal from "@/components/alert/admin/EditRoleModal.vue";
import EditPermissionModal from "@/components/alert/admin/EditPermissionModal.vue";
import { usePermissionService } from "@/stores/permissionService";
import { Search } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
const userStore = useUserStore();
const permissionService = usePermissionService();
const modalController = modalControllers();

// 统计数据响应式变量
const totalUsers = ref(0);
const activeUsers = ref(7);
const trainerCount = ref(0);
const internCount = ref(0);

// 用户列表和搜索
const userList = ref([]);
const searchQuery = ref("");
const editRoleModalRef = ref(null);
const editPermissionModalRef = ref(null); // 新增
const roleManagementModalRef = ref(null);
// 筛选表单
const filterForm = ref({
  role: "",
  department: "",
  status: "",
  registrationTime: "",
});

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 分页信息文本
const paginationText = computed(() => {
  const start =
    (pagination.value.currentPage - 1) * pagination.value.pageSize + 1;
  const end = Math.min(
    pagination.value.currentPage * pagination.value.pageSize,
    pagination.value.total,
  );
  // 在没有用户时，显示为 0
  const displayStart = pagination.value.total === 0 ? 0 : start;
  return `显示 ${displayStart} 到 ${end} 条，共 ${pagination.value.total} 条记录`;
});

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 过滤后的用户列表
const filteredUserList = computed(() => {
  if (!searchQuery.value) {
    return userList.value;
  }
  const query = searchQuery.value.toLowerCase();
  return userList.value.filter((user) =>
    user.username.toLowerCase().includes(query),
  );
});



// ...
const handlePermissions = (row) => {
  // 修改：调用新弹窗组件的 open 方法，并传入整行用户数据
  editPermissionModalRef.value?.open(row);
};

// 获取用户列表
const fetchUserList = async () => {
  try {
    const users = await permissionService.getUserList();
    userList.value = users;
    pagination.value.total = users.length;

    // 计算统计数据
    console.log("users:", users);
    totalUsers.value = users.length;
    const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
    //activeUsers.value = users.filter(user => 
    //   user.lastLogin && new Date(user.lastLogin) > oneDayAgo
    // ).length;
    activeUsers.value = users.filter((user) => user.status === "实习").length;
    trainerCount.value = users.filter(
      (user) => user.role === "培训导师",
    ).length;
    internCount.value = users.filter((user) => user.status === "实习").length;
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  }
};

// 编辑用户
const handleEdit = (row) => {
  modalController.openPopup("editUserModal");
};
// const handlePermissions = (row) => {
//   modalController.openPopup("editPermissionModal");
// };
// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.username} 吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 这里添加删除用户的逻辑
      ElMessage({
        type: "success",
        message: `用户 ${row.username} 已删除`,
      });
      // 刷新用户列表
      fetchUserList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    role: "",
    department: "",
    status: "",
    registrationTime: "",
  };
  searchQuery.value = "";
  fetchUserList();
};

// 应用筛选
const handleFilter = async () => {
  console.log("筛选条件:", filterForm.value);
  await fetchUserList();

  // 根据筛选条件过滤用户列表
  userList.value = userList.value.filter((user) => {
    // 角色筛选
    if (
      filterForm.value.role &&
      user.role !== mapValueToRoleName(filterForm.value.role)
    ) {
      return false;
    }

    // 状态筛选
    if (
      filterForm.value.status &&
      user.status !== mapValueToStatusName(filterForm.value.status)
    ) {
      return false;
    }

    // 注册时间筛选
    if (filterForm.value.registrationTime) {
      const registerDate = new Date(user.registerTime);
      const now = new Date();

      switch (filterForm.value.registrationTime) {
        case "7days":
          if (now - registerDate > 7 * 24 * 60 * 60 * 1000) return false;
          break;
        case "30days":
          if (now - registerDate > 30 * 24 * 60 * 60 * 1000) return false;
          break;
        case "90days":
          if (now - registerDate > 90 * 24 * 60 * 60 * 1000) return false;
          break;
      }
    }

    return true;
  });

  // 更新分页数据
  pagination.value.total = userList.value.length;
  pagination.value.currentPage = 1;
};

// 将选择值映射为角色名称
const mapValueToRoleName = (value) => {
  const roleMap = {
    admin: "系统管理员",
    trainer: "培训导师",
    student: "护理学员",
  };
  return roleMap[value] || "";
};

// 将选择值映射为状态名称
const mapValueToStatusName = (value) => {
  const statusMap = {
    // active: "活跃",
    // inactive: "未激活",
    // locked: "已锁定",
    // pending: "待审核",
    intern : "实习",
    formal : "正式",
  };
  return statusMap[value] || "";
};

// 获取角色标签类型
const getRoleTagType = (role) => {
  switch (role) {
    case "系统管理员":
      return "primary";
    case "培训导师":
      return "info";
    case "护理学员":
      return "success";
    default:
      return "";
  }
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case "活跃":
      return "success";
    case "未激活":
      return "info";
    case "已锁定":
      return "danger";
    case "待审核":
      return "warning";
    default:
      return "";
  }
};

// 处理页码变化
const handlePageChange = (newPage) => {
  pagination.value.currentPage = newPage;
};

// 监听搜索框变化
watch(searchQuery, (newVal) => {
  // 当搜索框为空时，重新获取所有用户
  if (!newVal) {
    fetchUserList();
  }
});
const handleRoleManagement = () => {
  roleManagementModalRef.value?.open();
};
onMounted(() => {
  fetchUserList();
  // 并行获取所有角色权限和所有可用权限
  Promise.all([
    permissionService.cacheAllRolePermissions(),
    permissionService.fetchAllPermissions()
  ]);
});
</script>

<style scoped>
/* 卡片头部样式 */
.card-header {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

/* 统计卡片样式 */
.stats-card {
  margin-bottom: 20px;
}

.stats-card .el-card__body {
  padding: 16px;
}

.stats-card .stat-icon {
  font-size: 24px;
  margin-right: 8px;
}

.stats-card .stat-value {
  font-size: 24px;
  font-weight: bold;
  margin: 8px 0 4px;
}

.stats-card .stat-label {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

/* 筛选表单样式 */
.filter-form {
  padding: 16px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
}

/* 表格样式 */
.el-table {
  margin-top: 0;
}

/* 操作按钮样式 */
.action-buttons .el-button {
  margin-right: 8px;
}

/* 分页样式 */
.el-pagination {
  margin-top: 16px;
  justify-content: flex-end;
}

/* 兼容 Bootstrap Icons */
.bi {
  vertical-align: -0.125em;
}

/* 布局样式 */
.admin-user-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 1rem;
}

.d-flex {
  display: flex;
}

.align-items-center {
  align-items: center;
}

.flex-grow-1 {
  flex-grow: 1;
}

.me-3 {
  margin-right: 0.75rem;
}

.flex-shrink-0 {
  flex-shrink: 0;
}

.text-xs {
  font-size: 0.75rem;
}

.font-weight-bold {
  font-weight: bold;
}

.text-primary {
  color: #4e73df;
}

.text-success {
  color: #1cc88a;
}

.text-info {
  color: #36b9cc;
}

.text-warning {
  color: #f6c23e;
}

.text-uppercase {
  text-transform: uppercase;
}

.mb-1 {
  margin-bottom: 0.25rem;
}

.h5 {
  font-size: 1.25rem;
}

.mb-0 {
  margin-bottom: 0;
}

.text-gray-800 {
  color: #5a5c69;
}

.fa-2x {
  font-size: 2em;
}

.text-gray-300 {
  color: #dddfeb;
}

.me-2 {
  margin-right: 0.5rem;
}

.me-1 {
  margin-right: 0.25rem;
}

.w-100 {
  width: 100%;
}

.shadow-sm {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.text-end {
  text-align: right;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.text-sm {
  font-size: 0.875rem;
}

.text-gray-500 {
  color: #b7b9cc;
}
</style>
